package cn.sxt.queue.consumer;

import lombok.SneakyThrows;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.io.IOException;

/**
 * 异步消费
 *
 * @author Mxb
 * @version 1.0
 * @date 2020/6/10 14:17
 */
public class TestSyncConsumer {
    //地址在mq conf activemq.xml里面找
    private static final String BROKER_URL = "tcp://39.99.166.61:61616";
    private static final String QUEUE_NAME = "mq-name-queue";

    public static void main(String[] args) throws JMSException, IOException {
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(BROKER_URL);

        Connection connection = connectionFactory.createConnection();

        connection.start();

        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        Queue queue = session.createQueue(QUEUE_NAME);

        MessageConsumer consumer = session.createConsumer(queue);

        // 设置监听 消费消息
        consumer.setMessageListener(new MessageListener() {

            @SneakyThrows
            @Override
            public void onMessage(Message message) {
                if (message != null && message instanceof TextMessage) {
                    TextMessage textMessage = (TextMessage) message;
                    System.out.println("接收到消息：" + textMessage.getText());
                }
            }
        });

        System.out.println("消息监听中：。。。。。。。。。。");
        System.in.read();

        //关闭资源
        consumer.close();
        session.close();
        connection.close();
        System.out.println("消息消费成功。。。");

    }
}
